<template>
	<div class="app-container">
		<div>
			<el-table v-loading="loading" :data="tournamentsList" border style="width: 100%" @expand-change="handleExpand">
				<el-table-column type="expand">
					<template slot-scope="scope">
						<template v-if="scope.row.videos">
							<div class="videos-container">
								<div v-for="(video, index) in parseVideos(scope.row.videos)" :key="index" class="video-item">
									<div class="video-name">{{ video.name }}</div>
									<video :src="baseUrl + video.url" controls class="video-player">您的浏览器不支持视频标签</video>
								</div>
							</div>
						</template>
						<el-empty v-else description="暂无视频"></el-empty>
					</template>
				</el-table-column>
				<el-table-column prop="tournamentName" label="赛事名称" width="180"> </el-table-column>
				<el-table-column prop="city" label="赛事地点" width="120"> </el-table-column>
				<el-table-column prop="hoster" label="主办方" width="120"> </el-table-column>
				<el-table-column prop="startTime" label="开始时间" width="160"> </el-table-column>
				<el-table-column prop="endTime" label="结束时间" width="160"> </el-table-column>
				<el-table-column prop="num" label="参赛队伍" width="100"> </el-table-column>
				<el-table-column align="center" label="操作">
					<template slot-scope="scope">
						<el-button size="mini" type="primary" @click="handleAddVideo(scope.row)">新增视频</el-button>
						<el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="query.pageNum"
				:page-sizes="[10, 20, 50, 100]"
				:page-size="query.pageSize"
				layout="->,total, sizes, prev, pager, next, jumper"
				:total="total">
			</el-pagination>
		</div>

		<!-- 新增视频对话框 -->
		<el-dialog title="新增视频" :visible.sync="dialogVisible" width="500px">
			<el-form :model="videoForm" :rules="rules" ref="videoForm" label-width="80px">
				<el-form-item label="视频名称" prop="name">
					<el-input v-model="videoForm.name" placeholder="请输入视频名称"></el-input>
				</el-form-item>
				<el-form-item label="视频链接" prop="url">
					<FileUpload v-model="videoForm.url" :fileType="['mp4']" :file-size="4 * 100" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="submitVideoForm">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import FileUpload from "./../../components/FileUpload/index.vue";
import { getTournamentsList, deleteTournament, createTournament } from "@/api/lv/saishi";

export default {
	components: { FileUpload },
	data() {
		return {
			tournamentsList: [],
			scheduleList: [],
			loading: false,
			query: {
				pageNum: 1,
				pageSize: 10
			},
			total: 0,
			baseUrl: process.env.VUE_APP_BASE_API,
			dialogVisible: false,
			currentRow: null,
			videoForm: {
				name: "",
				url: ""
			},
			rules: {
				name: [{ required: true, message: "请输入视频名称", trigger: "blur" }],
				url: [{ required: true, message: "请输入视频链接", trigger: "blur" }]
			}
		};
	},
	mounted() {
		this.getTournamentsList();
	},
	methods: {
		getTournamentsList() {
			this.loading = true;
			getTournamentsList(this.query)
				.then((res) => {
					this.tournamentsList = res.data.records;
					this.total = res.data.total;
					this.loading = false;
				})
				.catch(() => {
					this.loading = false;
				});
		},
		handleSizeChange(val) {
			this.query.pageSize = val;
			this.getTournamentsList();
		},
		handleCurrentChange(val) {
			this.query.pageNum = val;
			this.getTournamentsList();
		},
		handleDelete(row) {
			this.$confirm("确认要删除该赛事吗?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			})
				.then(() => {
					deleteTournament(row.id).then(() => {
						this.$message.success("删除成功");
						this.getTournamentsList();
					});
				})
				.catch(() => {
					this.$message.info("已取消删除");
				});
		},
		parseVideos(videosStr) {
			try {
				const videos = JSON.parse(videosStr);
				// 如果是数组直接返回，否则包装成数组
				return Array.isArray(videos) ? videos : [videos];
			} catch (e) {
				console.error("解析视频数据失败:", e);
				return [];
			}
		},
		handleExpand(row, expandedRows) {
			// 可以在这里处理展开行的逻辑
			console.log("展开行:", row);
		},
		handleAddVideo(row) {
			this.currentRow = row;
			this.dialogVisible = true;
			this.videoForm = {
				name: "",
				url: ""
			};
		},
		submitVideoForm() {
			this.$refs.videoForm.validate((valid) => {
				if (valid) {
					try {
						const currentVideos = this.currentRow.videos ? JSON.parse(this.currentRow.videos) : [];
						const videos = Array.isArray(currentVideos) ? currentVideos : [currentVideos];

						videos.push(this.videoForm);

						// 这里需要添加更新视频列表的API调用
						// updateTournamentVideos(this.currentRow.id, JSON.stringify(videos))
						//   .then(() => {
						//     this.$message.success('添加视频成功');
						//     this.getTournamentsList();
						//     this.dialogVisible = false;
						//   });

						// 临时方案：直接更新本地数据
						this.currentRow.videos = JSON.stringify(videos);
						console.log(this.currentRow);
						createTournament(this.currentRow).then(() => {
							this.$message.success("添加视频成功");
							this.getTournamentsList();
							this.dialogVisible = false;
						});
					} catch (e) {
						console.error("处理视频数据失败:", e);
						this.$message.error("添加视频失败");
					}
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.app-container {
	padding: 20px;
}

.videos-container {
	padding: 15px;
	display: flex;
	flex-wrap: wrap;
	gap: 15px;
}

.video-item {
	background: #f5f7fa;
	border-radius: 4px;
	padding: 8px;
	width: fit-content;
}

.video-name {
	font-size: 13px;
	color: #606266;
	margin-bottom: 6px;
	padding: 0 4px;
}

.video-player {
	width: 320px;
	height: 180px;
	border-radius: 4px;
	background: #000;
}
</style>
